package cn.turboinfo.fuyang.api.domain.mini.usecase.custom;

import cn.turboinfo.fuyang.api.domain.common.service.custom.ServiceCustomService;
import cn.turboinfo.fuyang.api.domain.common.service.staff.HousekeepingStaffService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.enumeration.custom.ServiceCustomStatus;
import cn.turboinfo.fuyang.api.entity.common.pojo.custom.ServiceCustom;
import cn.turboinfo.fuyang.api.entity.common.pojo.staff.HousekeepingStaff;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.util.Objects;

/**
 * 扫码开始服务(消费者扫家政服务人员的放心码)
 *
 * @author sunshow
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class MiniConsumerScanStartServiceCustomUseCase extends AbstractUseCase<MiniConsumerScanStartServiceCustomUseCase.InputData, MiniConsumerScanStartServiceCustomUseCase.OutputData> {

    private final ServiceCustomService serviceCustomService;

    private final HousekeepingStaffService housekeepingStaffService;

    @Override
    protected OutputData doAction(InputData inputData) {
        Long userId = inputData.getUserId();
        Long serviceCustomId = inputData.getServiceCustomId();
        String confidenceCode = inputData.getConfidenceCode();

        ServiceCustom serviceCustom = serviceCustomService.getByIdEnsure(serviceCustomId);

        if (!Objects.equals(userId, serviceCustom.getUserId())) {
            throw new IllegalArgumentException("用户ID不匹配");
        }
        if (serviceCustom.getCustomStatus() != ServiceCustomStatus.DISPATCHED_WAITING_SERVICE) {
            throw new IllegalArgumentException("服务订单状态不正确");
        }

        // 根据放心码获取家政服务人员信息
        HousekeepingStaff staff = housekeepingStaffService.findByCode(confidenceCode)
                .orElseThrow(() -> new RuntimeException("放心码未找到对应服务人员"));

        // 判断服务人员是否一致
        if (!Objects.equals(staff.getId(), serviceCustom.getStaffId())) {
            throw new RuntimeException("放心码和分配服务人员不一致");
        }

        // 认证通过开始服务
        serviceCustomService.startService(serviceCustomId, staff.getId());

        return OutputData.builder()
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        /**
         * 下单用户ID
         */
        @NotNull(message = "用户ID不能为空")
        @Positive
        private Long userId;

        /**
         * 服务订单ID
         */
        @NotNull(message = "服务订单不能为空")
        private Long serviceCustomId;

        /**
         * 放心码
         */
        @NotNull(message = "放心码不能为空")
        private String confidenceCode;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {


    }
}
